from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_categories():
    categories = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    for channel in channels:
        group_id = channel.group_id

        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

            cat_1 = channel.category

            categories[group_id]['channels'].append({
                'id': cat_1.id,
                'name': cat_1.name,
                'url': channel.url
            })

            for cat_2 in cat_1.subs.all():
                cat_2.sub_cats = []
                for cat_3 in cat_2.subs.all():
                    cat_2.sub_cats.append(cat_3)
                categories[group_id]['sub_cats'].append(cat_2)

    return categories